<?php
/**
 * Created by PhpStorm.
 * User: mww
 */
namespace app\index\controller;
use think\Controller;
use think\Db;
class Login extends Controller
{
    /**
     * 登录页面
     * @return mixed
     */
    public function indexLogin($phone='',$password=''){
        $this->assign('phone',$phone);
        $this->assign('password',$password);
        return $this->fetch('login/login');
    }

    /**
     * 登录操作
     * @return \think\response\Json
     */
    public function doLogin(){
        extract(input());
        $shop = Db::table('up_u_user')
            ->where('user_phone',$phone)
            ->field(['user_id','user_phone','user_password','user_status'])
            ->find();
        if(empty($shop)){
            return json(['code'=>-1,'msg'=>'该手机号尚未注册']);
        }
        if($shop['user_status'] != 1){
            return json(['code'=>-2,'msg'=>'该手机号已被冻结']);
        }
        $password2 = md5($password);
        if(strlen($password) == 32){
            $password2 = $password;
        }
        if($shop['user_password'] != $password2){
            return json(['code'=>-4,'msg'=>'密码错误']);
        }
        session('user_id',$shop['user_id']);
        return json(['code' => 200, 'url' => url('index/Index/index'), 'msg' => '登录成功！']);
    }

    /**
     * 找回密码
     * @return mixed|\think\response\Json
     */
    public function resetPwd(){
        if(request()->isAjax ()){
            extract(input());
            $user = Db::table('up_u_user')
                ->where('user_phone',$phone)
                ->field(['user_id','user_username','user_image','user_phone','user_token','user_password','user_del','user_status'])
                ->find();
            if(empty($user)){
                return json(['code'=>-1,'msg'=>'该手机号尚未注册']);
            }
            $d = Db::name('phonecode')->where(['phone'=>$phone,'status'=>0])->find();
            if(empty($d)){
                return json(['code'=>-2,'msg'=>'请先发送验证码']);
            }
            $t = time() - $d['time2'];
            if($t >= 900){
                return json(['code'=>-2,'msg'=>'验证码失效']);
            }
            if(md5($code) != $d['code']){
                return json(['code'=>-2,'msg'=>'验证码错误']);
            }
            // 启动事务
            Db::startTrans();
            try{
                Db::name('phonecode')->where(['phone'=>$phone])->setField ('status',1);
                Db::name('u_user')->where(['user_phone'=>$phone])
                    ->update(['user_password'=>md5($pwd)]);
                // 提交事务
                Db::commit();
                return json(['code'=>200,'url'=>url('home/Login/indexLogin'),'msg'=>'密码重置成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code'=>100,'msg'=>'密码重置失败']);
            }
        }
        return $this->fetch ('login/find_pwd');
    }


    /**
     * 注册1
     * @return mixed|\think\response\Json
     */
    public function select_role(){
        return $this->fetch ('login/select_role');
    }
    /**
     * 注册2
     * @return mixed|\think\response\Json
     */
    public function zhuce(){
        extract(input());
        if(request()->isAjax ()){
            $user = Db::table('up_u_user')
                ->where('user_phone',$phone)
                ->field(['user_id','user_username','user_image','user_phone','user_token','user_password','user_del','user_status'])
                ->find();
            if(!empty($user)){
                return json(['code'=>-1,'msg'=>'该手机号已注册']);
            }
            $d = Db::name('phonecode')->where(['phone'=>$phone,'status'=>0])->find();
            if(empty($d)){
                return json(['code'=>-2,'msg'=>'请先发送验证码']);
            }
            $t = time() - $d['time2'];
            if($t >= 900){
                return json(['code'=>-2,'msg'=>'验证码失效']);
            }
            if(md5($code) != $d['code']){
                return json(['code'=>-2,'msg'=>'验证码错误']);
            }
            // 启动事务
            Db::startTrans();
            try{
                $token = md5(date('YmdHis').rand(100000,999999));
                $data = array();
                $url =  http_type ();
                $data['user_password'] = md5($pwd);
                $data['user_time'] = date('Y-m-d H:i:s');
                $data['user_token'] = $token;
                $data['user_phone'] = $phone;
                $data['user_type'] = $type;
                $data['user_username'] = '用户' . rand(1000,9999);
                $data['user_image'] = $url . '/uploads/images/user2.png';
                if($type == 1){
                    $data['user_status'] = 1;
                    $data['user_image'] = $url . '/uploads/images/user1.png';
                }
                $uid = Db::name('u_user')->insertGetId($data);
                Db::table('up_phonecode')->where('phone',$phone)->update(['status'=>1]);
                // 提交事务
                Db::commit();
                session('user_id',$uid);//用户id
                session('user_username',$data['user_username']);//用户名称
                session('user_image','');//用户头像
                session('user_phone',$phone);//用户电话
                session('user_type',$type);//用户身份
                return json(['code'=>200,'url' => url('home/Index/index'),'msg'=>'注册成功']);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['code'=>100,'msg'=>'注册失败']);
            }
        }
        return $this->fetch ('login/register',['type'=>$type]);
    }

    /**
     * 发送验证码
     * @return \think\response\Json
     */
    public function sendCode(){
        extract(input());
        $user = Db::table('up_u_user')
            ->where('user_phone',$phone)
            ->field(['user_id','user_username','user_image','user_phone','user_token','user_password','user_del','user_status'])
            ->find();
        //$type == 1代表登录&找回密码  为2代表注册
        if(empty($user) && $type == 1){
            return json(['code'=>-1,'msg'=>'该手机号尚未注册']);
        }
        if(!empty($user) && $type == 2){
            return json(['code'=>-1,'msg'=>'该手机号已注册']);
        }

        $num = rand(1000,9999);
        $apibase = new \app\api\controller\Base();
        $sendres = $apibase->duaxin($phone,$num);
        if($sendres['code'] != '00000'){
            return json(['code'=>3,'msg'=>$sendres['msg']]);
        }else {
            //=============================
            $isset = Db::table('up_phonecode')->where('phone', $phone)->find();
            if ($isset) {
                $res = Db::table('up_phonecode')->where('phone', $phone)->update(['code' => md5($num), 'time2' => time(), 'status' => 0]);
            } else {
                $res = Db::table('up_phonecode')->insert(['phone' => $phone, 'code' => md5($num), 'time2' => time()]);
            }
            if (!$res) {
                return json(['code' => 31, 'msg' => '数据库操作失败']);
            }
            //===============================================
            return json(['code' => 200, 'msg' => md5($num)]);
        }

    }

    /*
     * 退出登录
     */
    public function loginOut(){
        session(null);
        $this->redirect(url('index/Login/indexLogin'));
    }
}